import { generateUUID } from "/@/utils/tool"
export default function (app) {
	// 自定义滚动条触底事件
	app.directive('scroll-loadend', {
		mounted(el, binding) {
			let timer = null
			const scrollHandler = () => {
				clearTimeout(timer)
				timer = setTimeout(() => {
					// 获取滚动条距离底部的距离
					const scrollBottom = el.scrollTop + el.clientHeight;
					const scrollHeight = el.scrollHeight;
					// 检查距离底部是否小于40 触发事件
					if (scrollHeight - scrollBottom < 40) {
						// 在这里可以执行你想要的操作
						if (binding.value && typeof binding.value === 'function') {
							binding.value()
						}
					}
					if (el._showBanckTop && typeof el._showBanckTop === 'function') {
						el._showBanckTop(el.scrollTop)
					}
				}, 200)
			};
			el.addEventListener('scroll', scrollHandler);
			// 在指令解绑时移除事件监听
			el._scrollHandler = scrollHandler;
		},
		unmounted(el) {
			el.removeEventListener('scroll', el._scrollHandler);
			if (el.bindName) {
				const bindEl = document.querySelector(`div[back-name="${el.bindName}"]`)
				document.body.removeChild(bindEl)
			}
		},
	})
	// 回到顶部 按钮 和上方滚动条触底事件为一套
	app.directive('back-top', {
		mounted(el, binding) {
			const newElement = document.createElement('div');
			const id = generateUUID();
			newElement.setAttribute('back-name', id);
			newElement.style.position = "absolute";
			newElement.style.width = "40px";
			newElement.style.height = "40px";
			newElement.style.right = "20px";
			newElement.style.bottom = "30px";
			newElement.style.backgroundColor = "#29ce92";
			newElement.style.borderRadius = "50%";
			newElement.style.cursor = "pointer";
			newElement.style.transition = "all 0.1s linear";
			newElement.style.boxShadow = "rgba(0, 0, 0, 0.5) 0px 0px 10px";
			newElement.style.display = "none";
			newElement.style.justifyContent = "center";
			newElement.style.alignItems = "center";
			newElement.style.transform = "rotate(-90deg)"
			const newElementI = document.createElement('i');
			newElementI.className = "iconfont icon-play"
			newElementI.style.color = "#ffffff"
			newElementI.style.fontSize = "18px"
			newElement.appendChild(newElementI);
			document.body.appendChild(newElement);
			el.showBackTop = false;
			// 监听点击回到顶部
			newElement.addEventListener('click', () => {
				el.scrollTo({
					top: 0,
					behavior: 'smooth'
				})
			})
			const showBanckTop = (scrollTop) => {
				if (scrollTop > 100) {
					newElement.style.display = "flex"
				} else {
					newElement.style.display = "none"
				}
			};
			el._showBanckTop = showBanckTop;
			el.bindName = id
		}
	})
}